//
//  ViewController.m
//  DistanceTool
//
//  Created by v_hefang on 2020/7/7.
//  Copyright © 2020 fh. All rights reserved.
//

#import "ViewController.h"
#import <QMapKit/QMapKit.h>

#define ViewWidth self.view.frame.size.width
#define ViewHeight self.view.frame.size.height

@interface ViewController () <QMapViewDelegate>

// MapView
@property (nonatomic, strong) QMapView *mapView;
@property (nonatomic, strong) UILongPressGestureRecognizer *addMarkerGesture;

// Polyline
@property (nonatomic, strong) QPolylineView *polylineView;
@property (nonatomic, strong) NSMutableArray *annotationArray;

// Distance
@property (nonatomic, assign) CLLocationDistance distance;

// Label
@property (nonatomic, strong) UILabel *distanceLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"距离计算";
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:@"撤销" style:UIBarButtonItemStyleDone target:self action:@selector(cancelPolyline)];
    UIBarButtonItem *deleteItem = [[UIBarButtonItem alloc] initWithTitle:@"重置" style:UIBarButtonItemStyleDone target:self action:@selector(deletePoyline)];
    self.navigationItem.rightBarButtonItems = @[cancelItem, deleteItem];
    
    [self setupMapView];
    [self setupDistanceLabel];
}


#pragma mark - Lazy Load
- (NSMutableArray *)annotationArray {
    if (_annotationArray == nil) {
        _annotationArray = [NSMutableArray array];
    }
    
    return _annotationArray;
}


#pragma mark - MapView
- (void)setupMapView {
    _distance = 0;
    
    
    CGFloat navBarHeight = self.navigationController.navigationBar.frame.size.height;
    CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    self.mapView = [[QMapView alloc] initWithFrame:CGRectMake(0, navBarHeight + statusBarHeight, ViewWidth, ViewHeight - navBarHeight - statusBarHeight)];
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
    
    [self setupLongPressGesture];
}


#pragma mark - Gesture
- (void)setupLongPressGesture {
    self.addMarkerGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(addMarker:)];
    self.addMarkerGesture.enabled = YES;
    [self.mapView addGestureRecognizer:self.addMarkerGesture];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)addMarker:(UILongPressGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        // 取点
        CLLocationCoordinate2D location = [self.mapView convertPoint:[gesture locationInView:self.mapView] toCoordinateFromView:self.mapView];
        QPointAnnotation *annotation = [[QPointAnnotation alloc] init];
        annotation.coordinate = location;
        
        // 添加到第一个路线中
        [self.annotationArray addObject:annotation];
        
        [self.mapView addAnnotation:annotation];
        [self handlePoyline];
    }
}


#pragma mark - Handle Polyline
- (void)handlePoyline {
    [self.mapView removeOverlays:self.mapView.overlays];
    
    // 判断是否有两个点以上
    if (self.annotationArray.count > 1) {
        NSInteger count = self.annotationArray.count;
        CLLocationCoordinate2D coords[count];
        for (int i = 0; i < count; i++) {
            QPointAnnotation *annotation = self.annotationArray[i];
            coords[i] = annotation.coordinate;
        }
        
        QPolyline *polyline = [[QPolyline alloc] initWithCoordinates:coords count:count];
        [self.mapView addOverlay:polyline];
    }
    
    // 计算距离
    [self countDistance];
}


#pragma mark - Map Delegate
- (QAnnotationView *)mapView:(QMapView *)mapView viewForAnnotation:(id<QAnnotation>)annotation {
    static NSString *fisrtLineId = @"FirstLine";
    if ([annotation isKindOfClass:[QPointAnnotation class]]) {
        QPinAnnotationView *annotationView = (QPinAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:fisrtLineId];
        if (annotationView == nil) {
            annotationView = [[QPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:fisrtLineId];
            annotationView.pinColor = QPinAnnotationColorRed;
        }
        return annotationView;
    }
    
    return nil;
}


- (QOverlayView *)mapView:(QMapView *)mapView viewForOverlay:(id<QOverlay>)overlay {
    if ([overlay isKindOfClass:[QPolyline class]]) {
        _polylineView = [[QPolylineView alloc] initWithPolyline:overlay];
        _polylineView.lineWidth = 5;
        _polylineView.strokeColor = [UIColor redColor];
        
        return _polylineView;
    }
    
    return nil;
}


#pragma mark - Handle Poyline
- (void)cancelPolyline {
    if (self.annotationArray.count > 1) {
        QPointAnnotation *annotaiton = [self.annotationArray lastObject];
        [self.mapView removeAnnotation:annotaiton];
        [self.annotationArray removeLastObject];
        [self handlePoyline];
    } else {
        [self deletePoyline];
    }
}

- (void)deletePoyline {
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
    [self.annotationArray removeAllObjects];
    
    _distance = 0;
    [self updateDistanceLabel];
}


#pragma mark - Distance Label
- (void)setupDistanceLabel {
    self.distanceLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ViewWidth, 44)];
    self.distanceLabel.textAlignment = NSTextAlignmentCenter;
    self.distanceLabel.textColor = [UIColor blackColor];
    self.distanceLabel.backgroundColor = [UIColor whiteColor];
    self.distanceLabel.text = @"总距离: 0米";
    
    [self.mapView addSubview:self.distanceLabel];
}


#pragma mark - Distance
- (void)countDistance {
    _distance = 0;
    
    NSInteger count = self.annotationArray.count;
    
    for (int i = 0; i < count - 1; i++) {
        QPointAnnotation *annotation1 = self.annotationArray[i];
        QPointAnnotation *annotation2 = self.annotationArray[i + 1];
        _distance += QMetersBetweenCoordinates(annotation1.coordinate, annotation2.coordinate);
    }
    
    [self updateDistanceLabel];
}

- (void)updateDistanceLabel {
    self.distanceLabel.text = [NSString stringWithFormat:@"总距离: %.1f米", _distance];
}

@end
